<template>
	<el-dialog
	  title="填写"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
	  width="70%">

    <el-row>
      <el-col :span="1">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      </el-col>
      <el-col :span="23">
        <el-checkbox-group v-model="checkBoxItem" size="medium" @change="showRow">
          <el-checkbox v-for="item in allItem" :label="item" :key="item.performanceId">{{item.inspectionItemName}}</el-checkbox>
        </el-checkbox-group>
      </el-col>
    </el-row>

    <el-card>
      <div slot="header">
        <span>
        {{ childDataForm.productName }}
        &nbsp;&nbsp;&nbsp;&nbsp;
        {{ childDataForm.batchNum }}
        </span>
      </div>
      <div>
        <el-table
        	:data="dataList"
        	border
          fit
          highlight-current-row
          style="width: 100%">
          <el-table-column
              label="编号"
              header-align="center"
              align="center">
            <el-table-column
              prop="performanceId"
              header-align="center"
              align="center"
              label="快捷选项"
              width="100">
            </el-table-column>
          </el-table-column>
          <el-table-column
            prop="workshopName"
            header-align="center"
            align="center"
            label="生产车间">
          </el-table-column>
          <el-table-column
            prop="inspectionItemName"
            header-align="center"
            align="center"
            label="检验项名称">
          </el-table-column>

          <el-table-column
              label="检验人"
              header-align="center"
              align="center">
            <el-table-column
              prop="inspectionUserId"
              header-align="center"
              align="center"
              width="200">
              <template slot="header" slot-scope="scope">
                <el-select v-model="allInspectionUser" value-key="userId" @change="changeAllInspectionUser" filterable placeholder="检验人">
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.name + '(' + item.username + ')'"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
              <template slot-scope="scope">
                <el-select v-model="scope.row.inspectionUser" value-key="userId" @change="setInspectionUser(scope.$index)" filterable placeholder="检验人">
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.name + '(' + item.username + ')'"
                    :value="item">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column
              label="检验时间"
              header-align="center"
              align="center">
            <el-table-column
              prop="time"
              header-align="center"
              align="center"
              width="250">
              <template slot="header" slot-scope="scope">
                <el-date-picker
                  v-model="allTime"
                  type="daterange"
                  @change="setAllTime"
                  range-separator="-"
                  start-placeholder="开始时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  end-placeholder="结束时间"
                  :picker-options="pickerOptions"
                  style="width: 100%;">
                </el-date-picker>
              </template>
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.time"
                  type="daterange"
                  @change="setTime(scope.$index)"
                  range-separator="-"
                  start-placeholder="开始时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  end-placeholder="结束时间"
                  :picker-options="pickerOptions"
                  style="width: 100%;">
                </el-date-picker>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column
            prop="itemStatus"
            header-align="center"
            align="center"
            label="保存状态"
            width="80">
            <template slot-scope="{row}">
              <i v-if="row.itemStatus == 2" style="color: #67C23A;font-size: 25px;" class="el-icon-check"></i>
              <i v-else style="color: #F56C6C;font-size: 25px;" class="el-icon-close"></i>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
	  <span slot="footer" class="dialog-footer">
	    <el-button type="primary" class="pan-btn primary-btn" @click="close">确 定</el-button>
  	</span>
	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getPerformanceList,getUserList,performanceWrite } from '@/api/check'
	import { CODE_OK } from '@/common/js/config'
  import { isBlank,parseTime,dateCompare } from '@/common/js/utils'
	export default {
		data() {
			return {
				visible: false,
        isIndeterminate: true,
        checkBoxItem: [],
        allItem: [],
        checkAll: false,
        dataList: [],
        userList: [],
        allInspectionUser: '',
        allTime: '',
        saveQueue: []
			}
		},
		props: ["childDataForm"],
		created() {
			if (!isBlank(this.childDataForm)) {
        this.getInfo()
        this.visible = true
			}
		},
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
		methods: {
      getInfo() {
        const params = {
          page: 1,
          limit: 999,
          inspectionGroupIds: this.childDataForm.inspectionGroupId,
          productName: this.childDataForm.productName,
          batchNum: this.childDataForm.batchNum,
          isWrite: 0
        }
        getPerformanceList(params).then(res => {
          if (res.code === CODE_OK) {
          	this.dataList = res.page.list.map(item => {
              if (item.itemStatus == 2) {
                this.$set(item, 'inspectionUser', {
                  userId: item.inspectionUserId,
                  name: item.inspectionUserName
                })
                this.$set(item, 'time', [
                  item.startTime,
                  item.endTime
                ])
              }
              return item
            })
            this.init()
          }else{
          	this.$message.error(res.msg)
          }
        })
        const params2 = {
          groupId: this.childDataForm.inspectionGroupId
        }
        getUserList(params2).then(res => {
          if (res.code === CODE_OK) {
            this.userList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      init() {
        this.allItem = JSON.parse(JSON.stringify(this.dataList))
        for (let item of this.allItem) {
          this.checkBoxItem.push(item)
        }
        this.checkAll = true
        this.isIndeterminate = false
      },
      changeAllInspectionUser() {
        for (let i=0,j=this.dataList.length; i<j; i++) {
          if (this.dataList[i].itemStatus == 1) {
            this.$set(this.dataList[i],'inspectionUser',{
              userId: this.allInspectionUser.userId,
              name: this.allInspectionUser.name
            })
            this.dataList[i].inspectionUserId = this.dataList[i].inspectionUser.userId
            this.dataList[i].inspectionUserName = this.dataList[i].inspectionUser.name
            this.saveRow(i,false)
          }
        }
        this.write()
      },
      setInspectionUser(index) {
        this.dataList[index].inspectionUserId = this.dataList[index].inspectionUser.userId
        this.dataList[index].inspectionUserName = this.dataList[index].inspectionUser.name
        this.saveRow(index,true)
      },
      setAllTime() {
        for (let i=0,j=this.dataList.length; i<j; i++) {
          if (this.dataList[i].itemStatus == 1) {
            this.$set(this.dataList[i],'time',JSON.parse(JSON.stringify(this.allTime)))
            this.dataList[i].startTime = this.dataList[i].time[0]
            this.dataList[i].endTime = this.dataList[i].time[1]
            this.saveRow(i,false)
          }
        }
        this.write()
      },
      setTime(index) {
        let row = this.dataList[index]
        if (!isBlank(row.time)) {
          this.dataList[index].startTime = row.time[0]
          this.dataList[index].endTime = row.time[1]
          this.saveRow(index,true)
        }
      },
      write() {
        if (this.saveQueue.length == 0) {
          return
        }
        let index = this.saveQueue.pop()
        let row = this.dataList[index]
        performanceWrite(row).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('保存成功')
            this.dataList[index].itemStatus = 2
            for (let i=0,j=this.allItem.length; i<j; i++) {
              if (row.performanceId === this.allItem[i].performanceId) {
                this.allItem[i] = row
              }
            }
          }else{
            this.$message.error(res.msg)
          }
          this.write()
        })
      },
      saveRow(index,val) {
        if (this.rowVerify(this.dataList[index])) {
          this.saveQueue.push(index)
          if (val) {
            this.write()
          }
        }
      },
      rowVerify(row) {
        if (isBlank(row.inspectionUserId)) {
          // this.$message.error("检验人不能为空")
          return false
        }
        if (isBlank(row.startTime)) {
          // this.$message.error("检验时间不能为空")
          return false
        }else{
          if (!dateCompare(this.childDataForm.sendTime, row.startTime)) {
            this.$message.error("检验开始日期必须晚于分样日期: " + this.childDataForm.sendTime)
            return false
          }
        }
        return true
      },
      close() {
      	this.$emit('refreshData')
        this.$emit('close')
      	this.visible = false
      },
      updateItems(arr) {
        this.dataList = arr
      },
      showRow(arr) {
        let checkedCount = arr.length
        this.checkAll = checkedCount === this.allItem.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allItem.length
        this.updateItems(arr)
      },
      handleCheckAllChange(val) {
        this.checkBoxItem = []
        if (val) {
          for (let i=0,j=this.allItem.length; i<j; i++) {
            this.checkBoxItem.push(this.allItem[i])
          }
        }
        this.isIndeterminate = false
        let arr = val ? JSON.parse(JSON.stringify(this.allItem)) : []
        this.updateItems(arr)
      }
    }
	}
</script>

<style>
</style>
